﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Threading;
using SilverlightProgressFeedback.Web.ProgressFeedback;
using Monitor = SilverlightProgressFeedback.Web.ProgressFeedback.Monitor;

namespace SilverlightProgressFeedback.Web
{
    [ServiceContract(Namespace = "")]    
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1
    {
        private static readonly Monitor _monitor = new Monitor();

        [OperationContract]
        public void AbortProcess(Guid progressFeedbackKey)
        {
            ProgressInfo info = _monitor.GetInfo(progressFeedbackKey);
            if (info != null)
            {
                info.Abort = true;
            }
        }

        [OperationContract]
        public ProgressInfo GetProcessInfo(Guid progressFeedbackKey, int delayms)
        {
            Thread.Sleep(delayms);
            return _monitor.GetInfo(progressFeedbackKey);
        }

        [OperationContract]
        public string SlowProcess(Guid progressFeedbackKey, int inputVariable)
        {
            ProgressInfo info = _monitor.RegisterNewProgressProcess(progressFeedbackKey);

            info.AddMessage("Starting");
            const int max = 30000;
            int tens = -1;

            for (int i = 0; i < max; i++)
            {
                double percentage = (double)i / max;
                int currentTens = (int)Math.Round(percentage * 10) * 10;
                if (tens != currentTens)
                {
                    info.AddMessage("Reached {0}%", currentTens);
                }
                tens = currentTens;

                // This part is what generates the feedback
                info.Description = string.Format("At {0:0.00%}", percentage);
                Thread.Sleep(50);

                // Every once in a while, check if the user requested an abort
                if (info.Abort)
                {
                    throw new ProcessAbortedException();
                }
            }

            return "SlowProcess 1 is DONE! Variable was " + inputVariable;
        }
    }
}
